package com.world.lzh.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author lzh
 * @Date 2022/5/6 - 9:05
 * @Description
 * @Version 1.0.0
 **/
@RestController
public class FileController {

    public static final String FILE_ROOT_PATH = "D:/fileUpload/";

    @RequestMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        //创建一个时间字符串，用于区分文件夹
        String dateStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //拼接路径
        String uri = FILE_ROOT_PATH + dateStr + "/";
        //判断文件夹是否存在，如果不存在，就新建
        File dir = new File(uri);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        String newFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        File f = new File(dir.getPath() + File.separator + newFileName);
        FileUtils.copyInputStreamToFile(file.getInputStream(), f);
        String fileUrl = uri + newFileName;
        return fileUrl;
    }

    @RequestMapping("/download")
    public void download(@RequestParam("text") String text, HttpServletRequest request, HttpServletResponse response) {
        File file = new File(text);
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
